package com.xu.tools.util;

import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 打印各种对象信息
 *
 * @author xuguan
 * @since 2023/8/25
 */
public class PrintUtil {
    private static final String EMPTY_STRING = "";
    private static final String ARRAY_START = "{";
    private static final String ARRAY_END = "}";
    private static final String EMPTY_ARRAY = "{}";
    private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
    private static final String MAP_ELEMENT_SEPARATOR = ": ";

    public static void printlnObj(Object obj) {
        String str;
        if (obj == null) {
            str = EMPTY_STRING;
        } else if (obj instanceof String) {
            str = (String) obj;
        } else if (obj instanceof Serializable) {
            str = JsonUtil.toJsonString(obj);
        } else {
            str = ObjectUtils.getDisplayString(obj);
        }
        System.out.println(str);
    }

    public static void printlnCollection(Collection<?> collection) {
        String str;
        if (CollectionUtils.isEmpty(collection)) {
            str = EMPTY_ARRAY;
        } else {
            String content = collection
                    .stream()
                    .map(ObjectUtils::getDisplayString)
                    .collect(Collectors.joining(ARRAY_ELEMENT_SEPARATOR));
            str = ARRAY_START + content + ARRAY_END;
        }
        System.out.println(str);
    }

    public static void printlnMap(Map<?, ?> map) {
        String str;
        if (CollectionUtils.isEmpty(map)) {
            str = EMPTY_ARRAY;
        } else {
            String content = map.entrySet()
                    .stream()
                    .map(entry -> entry.getKey() + MAP_ELEMENT_SEPARATOR + entry.getValue())
                    .collect(Collectors.joining(ARRAY_ELEMENT_SEPARATOR));
            str = ARRAY_START + content + ARRAY_END;
        }
        System.out.println(str);
    }
}
